<?php

Yii::import("application.components.evaluators.GraderBase");

/**
 * Kelas konret untuk grader simple
 * Objek SimpleGrader akan menjalankan program hasil kompilasi dan mengujinya dengan test cases
 * Setelah grading, hasil grading dapat diambil berupa array
 */
class BatchGrader extends GraderBase {

    public function __construct($pCompiler) {
        parent::__construct($pCompiler);
    }

    protected function afterGrade() {
        parent::afterGrade();
    }

    protected function beforeGrade() {
        //extract evaluation set data
        $gradingDir = $this->compiler->getGradingDirectory();
        $tmpTestCasePath = $gradingDir . "/tc.zip";
        file_put_contents($tmpTestCasePath, $this->compiler->getRequestModel()->evaluationset->file);
        exec("unzip -o " . $tmpTestCasePath . " -d $gradingDir/tc");
    }

    protected function doGrade() {
        $gradeOutput = $this->compiler->getGradingDirectory() . "/grade.out";

        $tcDirPath = $this->compiler->getGradingDirectory() . "/tc/";
        $tc = 1;
        $found = false;
        $tcResult = array();
        $total = 0;
        $right = 0;
        do {
            $found = file_exists($tcDirPath . $tc . ".score");

            if ($found) {
                $currentTcInPath = $tcDirPath . $tc . ".in";
                $currentTcOutPath = $tcDirPath . $tc . ".out";
                $currentTcScore = file_get_contents($tcDirPath . $tc . ".score");
                $currentTcScore += 0;
                $total += $currentTcScore;

                $return = $this->execute("bin/mo-eval/mo-evalbox -e -w 30 -m 32000000 -o $gradeOutput -- " . $this->compiler->getOutputFilePath() . " < $currentTcInPath 2>&1", $output);

                if ($return == 0) {
                    if (file_get_contents($gradeOutput) == file_get_contents($currentTcOutPath)) { ///Matched
                        $tcResult[$currentTcInPath] = "Correct ($currentTcScore)\n" . $output;
                        $right += $currentTcScore;
                    } else {
                        $tcResult[$currentTcInPath] = "Wrong answer\n" . $output;
                    }
                } else {
                    $tcResult[$currentTcInPath] = "Execution failure\n" . $output;
                }
            }

            $tc++;
        } while ($found);
        /* $return = $this->execute("/bin/mo-evalbox -w 30 -o $gradeOutput -- /bin/sh " . $this->compiler->getExecutionScriptPath() . " 2>&1", $output);
          $this->gradeResult['output'] = file_get_contents($gradeOutput);
          $this->gradeResult['return'] = $return;
          $this->gradeResult['sandboxoutput'] = $output; */
        $this->gradeResult['detailedresult'] = $tcResult;
        $this->gradeResult['score'] = $right;
        $this->gradeResult['sandboxoutput'] = $output;
    }

}

?>
